# *--encoding:UTF-8--*
from config import *
from urllib.parse import urlencode
import requests,os
import time,random
import prettytable as pt

class Spider(object):
    def __init__(self, fs=None, ts=None, date=None):

        self.fs = fs
        self.ts = ts
        self.date = date
        self.tb = pt.PrettyTable()

    # 请求详情页面
    def RequestIndex(self):

        params = {

            "leftTicketDTO.train_date": self.date,
            "leftTicketDTO.from_station": cityCodes[self.fs],
            "leftTicketDTO.to_station": cityCodes[self.ts],
            "purpose_codes": "ADULT",
        }

        payload = urlencode(params)

        try:
            r = requests.get(url=domain["search_url"] + payload, headers=header)

            if r.status_code == 200 and r.json()["httpstatus"] == 200:

                result = r.json()["data"]["result"]

                tables = self.ParseIndex( result )

                print( tables )

        except Exception as e:

            print("查询的时间/有误请核实后再进行查询")

            print("行程日期:%s\n出发地点:%s\n目的地点:%s"%( self.date,self.fs,self.ts))

    def ParseIndex(self,result):

        self.tb.field_names = tbs

        for item in result:

            tmp_list = (item.split("|"))

            self.tb.add_row([tmp_list[3], tmp_list[8], tmp_list[9], tmp_list[10],
                             "--" if len(tmp_list[31]) == 0 else tmp_list[31],
                             "--" if len(tmp_list[30]) == 0 else tmp_list[30],
                             "--" if len(tmp_list[23]) == 0 else tmp_list[23],
                             "--" if len(tmp_list[28]) == 0 else tmp_list[28],
                             "--" if len(tmp_list[29]) == 0 else tmp_list[29],
                             "--" if len(tmp_list[26]) == 0 else tmp_list[26],

                             ]
                            )

        return (self.tb)

if __name__ == '__main__':


    fs = input("请输入乘车地点:")
    ts = input("请输入目的地点:")
    date = input("请输入乘车日期:")

    print("正在为您查询%s%s到%s所有车辆信息..."%(date,fs,ts))

    time.sleep( random.randint(3,5))

    s = Spider( fs,ts,date)

    s.RequestIndex()



